/***************************************************
 ** @Desc : This file for 充值代付记录
 ** @Time : 2019.04.10 15:55 
 ** @Author : Joker
 ** @File : record
 ** @Last Modified by : Joker
 ** @Last Modified time: 2019.04.10 15:55
 ** @Software: GoLand
****************************************************/
package controllers

import (
	"os"
	"recharge/controllers/condition"
	"recharge/controllers/implement"
	"recharge/models"
	"recharge/sys"
	"recharge/utils"
	"strconv"
	"strings"
	"time"
)

type Record struct {
	KeepSession
}

var recordFac = condition.RecordFactor{}
var recordImpl = implement.RecordImpl{}

// 充值记录展示界面
// @router /merchant/list_recharge/ [get]
func (the *Record) ListRechargeUI() {
	userName := the.GetSession("userName")
	if userName != nil {
		the.Data["userName"] = userName.(string)
	}

	right := the.GetSession("FilterRight")
	if right != nil {
		the.Data["right"] = right.(int)
	}

	the.Data["status"] = utils.GetOrderStatus()

	the.TplName = "recharge_record.html"
}

// 充值记录查询分页
// @router /merchant/list_recharge_record/?:params [get]
func (the *Record) QueryAndListPage() {
	//分页参数
	page, _ := strconv.Atoi(the.GetString("page"))
	limit, _ := strconv.Atoi(the.GetString("limit"))
	if limit == 0 {
		limit = 20
	}

	//查询参数
	in := make(map[string]interface{})
	inT := models.UserReconcileDao{}
	MerchantNo := strings.TrimSpace(the.GetString("MerchantNo"))
	MerchantName := strings.TrimSpace(the.GetString("MerchantName"))
	start := strings.TrimSpace(the.GetString("start"))
	end := strings.TrimSpace(the.GetString("end"))
	uStatus := the.GetString("uStatus")

	in["re_order_id__icontains"] = MerchantNo
	in["re_account_name"] = MerchantName

	if start != "" {
		in["edit_time__gte"] = start
	}
	if end != "" {
		in["edit_time__lte"] = end
	}

	in["status"] = uStatus

	//TODO:管理员能看所有记录
	FilterRight := the.GetSession("FilterRight")
	if FilterRight.(int) > 0 {
		userId := the.GetSession("userId")
		in["user_id"] = userId.(int)
	}

	//TODO:管理员能搜索用户
	userInfo := models.UserInfo{}
	_userName := the.GetString("_userName")
	if FilterRight.(int) <= 0 {
		if _userName != "" {
			userInfo = userMdl.SelectOneUserByUserName(_userName)
			in["user_id"] = userInfo.Id
			inT.UserId = strconv.Itoa(userInfo.Id)
		}
	}

	//计算分页数
	count := rechargeMdl.SelectRechargeRecordPageCount(in)
	totalPage := count / limit // 计算总页数
	if count%limit != 0 { // 不满一页的数据按一页计算
		totalPage++
	}

	//数据获取
	var list []models.RechargeRecord
	if page <= totalPage {
		list = rechargeMdl.SelectRechargeRecordListPage(in, limit, (page-1)*limit)
		uId := -9
		for i := 0; i < len(list); i++ {
			//若前一个ID不等于后一个,则查询数据库
			if uId != list[i].UserId {
				userInfo, _ = userMdl.SelectOneUserById(list[i].UserId)
				uId = list[i].UserId
			}
			list[i].UserName = userInfo.UserName
		}
	}

	var rechargeT models.Count
	if start == "" {
		start = globalMethod.GetNowTimeV3() + " 00:01:05"
	}
	if end == "" {
		end = globalMethod.GetNowTime()
	}
	inT.EditTime = start
	inT.EditTimeEnd = end
	if FilterRight.(int) <= 0 {
		//计算 成功充值金额
		inT.Status = utils.S //成功充值金额
		rechargeT = reconDao.SelectCountSuccessRecharge(inT)
	}

	//数据回显
	out := make(map[string]interface{})
	out["limit"] = limit //分页数据
	out["page"] = page
	out["totalPage"] = totalPage
	out["_r_rechargeT"] = globalMethod.MoneyYuanToString(rechargeT.Total)
	out["root"] = list //显示数据

	the.Data["json"] = out
	the.ServeJSON()
	the.StopRun()
}

// 代付记录展示界面
// @router /merchant/list_pay_ui/ [get]
func (the *Record) ListPayUI() {
	userName := the.GetSession("userName")
	if userName != nil {
		the.Data["userName"] = userName.(string)
	}

	right := the.GetSession("FilterRight")
	if right != nil {
		the.Data["right"] = right.(int)
	}

	the.Data["status"] = utils.GetOrderStatus()

	the.TplName = "withdraw_record.html"
}

// 代付记录查询分页
// @router /merchant/list_pay/?:params [get]
func (the *Record) PayQueryAndListPage() {
	//分页参数
	page, _ := strconv.Atoi(the.GetString("page"))
	limit, _ := strconv.Atoi(the.GetString("limit"))
	if limit == 0 {
		limit = 20
	}

	//查询参数
	in := make(map[string]interface{})
	inT := models.UserReconcileDao{}
	MerchantNo := strings.TrimSpace(the.GetString("MerchantNo"))
	MerchantName := strings.TrimSpace(the.GetString("MerchantName"))
	start := strings.TrimSpace(the.GetString("start"))
	end := strings.TrimSpace(the.GetString("end"))
	uStatus := the.GetString("uStatus")

	in["wh_order_id__icontains"] = MerchantNo
	in["wh_account_name"] = MerchantName

	if start != "" {
		in["edit_time__gte"] = start
	}
	if end != "" {
		in["edit_time__lte"] = end
	}

	in["status"] = uStatus

	//TODO:管理员能看所有记录
	FilterRight := the.GetSession("FilterRight")
	if FilterRight.(int) > 0 {
		userId := the.GetSession("userId")
		in["user_id"] = userId.(int)
	}

	//TODO:管理员能搜索用户
	userInfo := models.UserInfo{}
	_userName := the.GetString("_userName")
	if FilterRight.(int) <= 0 {
		if _userName != "" {
			userInfo = userMdl.SelectOneUserByUserName(_userName)
			in["user_id"] = userInfo.Id
			inT.UserId = strconv.Itoa(userInfo.Id)
		}
	}

	//计算分页数
	count := payMdl.SelectWithdrawRecordPageCount(in)
	totalPage := count / limit // 计算总页数
	if count%limit != 0 { // 不满一页的数据按一页计算
		totalPage++
	}

	//数据获取
	var list []models.WithdrawRecord
	if page <= totalPage {
		list = payMdl.SelectWithdrawRecordListPage(in, limit, (page-1)*limit)
		uId := -9
		if len(list) > 0 {
			for i := 0; i < len(list); i++ {
				//若前一个ID不等于后一个,则查询数据库
				if uId != list[i].UserId {
					userInfo, _ = userMdl.SelectOneUserById(list[i].UserId)
					uId = list[i].UserId
				}
				list[i].UserName = userInfo.UserName
			}
		}
	}

	var rechargeT models.Count
	if start == "" {
		start = globalMethod.GetNowTimeV3() + " 00:01:05"
	}
	if end == "" {
		end = globalMethod.GetNowTime()
	}
	inT.EditTime = start
	inT.EditTimeEnd = end
	if FilterRight.(int) <= 0 {
		//计算 代付金额
		inT.Status = utils.S
		rechargeT = reconDao.SelectCountSuccessPay(inT)
	}

	//数据回显
	out := make(map[string]interface{})
	out["auth"] = the.GetSession("FilterRight").(int) + 100 //权限

	out["limit"] = limit //分页数据
	out["page"] = page
	out["totalPage"] = totalPage
	out["_p_rechargeT"] = globalMethod.MoneyYuanToString(rechargeT.Total)
	out["root"] = list //显示数据

	the.Data["json"] = out
	the.ServeJSON()
	the.StopRun()
}

// 根据时间统计充值、代付金额
// @router /merchant/count_all_recharge_pay/?:params [get,post]
func (the *Record) ShowUserTodayAmount() {
	userId := the.GetSession("userId").(int)

	userInfo, _ := userMdl.SelectOneUserById(userId)

	start := strings.TrimSpace(the.GetString("start"))
	end := strings.TrimSpace(the.GetString("end"))

	if start == "" {
		start = globalMethod.GetNowTimeV3() + " 00:01:05"
	}
	if end == "" {
		end = globalMethod.GetNowTime()
	}

	in := models.UserReconcileDao{}
	in.EditTime = start
	in.EditTimeEnd = end
	in.UserId = strconv.Itoa(userId)
	in.Status = utils.S

	// 充值
	cr := reconDao.SelectCountSuccessRecharge(in)

	// 转账
	ct := reconDao.SelectCountSuccessTransfer(in)

	//代付
	cp := reconDao.SelectCountSuccessPay(in)

	//费率
	feeR := cr.Total*userInfo.RechargeRate*0.001 + float64(cr.Length)*userInfo.RechargeFee
	feeT := ct.Total * userInfo.RechargeRate * 0.001
	feeP := float64(cp.Length) * userInfo.PayFee
	fee := feeP + feeR + feeT

	//数据回显
	out := make(map[string]interface{})
	out["todayRecharge"] = globalMethod.MoneyYuanToString(cr.Total)
	out["todayTransfer"] = globalMethod.MoneyYuanToString(ct.Total)
	out["recharge"] = globalMethod.MoneyYuanToString(cr.Total + ct.Total)
	out["pay"] = globalMethod.MoneyYuanToString(cp.Total)
	out["fee"] = globalMethod.MoneyYuanToString(fee)
	out["lenR"] = cr.Length
	out["lenT"] = ct.Length
	out["lenP"] = cp.Length
	out["code"] = utils.SUCCESS_FLAG
	the.Data["json"] = out
	the.ServeJSON()
	the.StopRun()
}

// 转账记录展示界面
// @router /transfer/show_transfer_record/ [get]
func (the *Record) ListTransferUI() {
	userName := the.GetSession("userName")
	if userName != nil {
		the.Data["userName"] = userName.(string)
	}

	right := the.GetSession("FilterRight")
	if right != nil {
		the.Data["right"] = right.(int)
	}

	the.Data["status"] = utils.GetOrderStatus()

	the.TplName = "transfer_record.html"
}

// 转账记录查询分页
// @router /transfer/list_transfer/?:params [get]
func (the *Record) TransferQueryAndListPage() {
	//分页参数
	page, _ := strconv.Atoi(the.GetString("page"))
	limit, _ := strconv.Atoi(the.GetString("limit"))
	if limit == 0 {
		limit = 20
	}

	//查询参数
	in := make(map[string]interface{})
	inT := models.UserReconcileDao{}
	orderId := strings.TrimSpace(the.GetString("MerchantName"))
	start := strings.TrimSpace(the.GetString("start"))
	end := strings.TrimSpace(the.GetString("end"))
	uStatus := the.GetString("uStatus")

	in["tr_order_id__icontains"] = orderId

	if start != "" {
		in["edit_time__gte"] = start
	}
	if end != "" {
		in["edit_time__lte"] = end
	}

	in["status"] = uStatus

	//TODO:管理员能看所有记录
	FilterRight := the.GetSession("FilterRight")
	if FilterRight.(int) > 0 {
		userId := the.GetSession("userId")
		in["user_id"] = userId.(int)
	}

	//TODO:管理员能搜索用户
	userInfo := models.UserInfo{}
	_userName := the.GetString("_userName")
	if FilterRight.(int) <= 0 {
		if _userName != "" {
			userInfo = userMdl.SelectOneUserByUserName(_userName)
			in["user_id"] = userInfo.Id
			inT.UserId = strconv.Itoa(userInfo.Id)
		}
	}

	//计算分页数
	count := transferMdl.SelectTransferRecordPageCount(in)
	totalPage := count / limit // 计算总页数
	if count%limit != 0 { // 不满一页的数据按一页计算
		totalPage++
	}

	//数据获取
	var list []models.TransferRecord
	if page <= totalPage {
		list = transferMdl.SelectTransferRecordListPage(in, limit, (page-1)*limit)
		uId := -9
		for i := 0; i < len(list); i++ {
			//若前一个ID不等于后一个,则查询数据库
			if uId != list[i].UserId {
				userInfo, _ = userMdl.SelectOneUserById(list[i].UserId)
				uId = list[i].UserId
			}
			list[i].UserName = userInfo.UserName
		}
	}

	var rechargeT models.Count
	if start == "" {
		start = globalMethod.GetNowTimeV3() + " 00:01:05"
	}
	if end == "" {
		end = globalMethod.GetNowTime()
	}
	inT.EditTime = start
	inT.EditTimeEnd = end
	if FilterRight.(int) <= 0 {
		//计算 成功转账金额
		inT.Status = utils.S //成功金额
		rechargeT = reconDao.SelectCountSuccessTransfer(inT)
	}

	//数据回显
	out := make(map[string]interface{})
	out["limit"] = limit //分页数据
	out["page"] = page
	out["totalPage"] = totalPage
	out["rechargeT"] = globalMethod.MoneyYuanToString(rechargeT.Total)
	out["root"] = list //显示数据

	the.Data["json"] = out
	the.ServeJSON()
	the.StopRun()
}

// 记录导出为Excel
// @router /merchant/make_excel/?:params [get]
func (the *Record) MakeExcelForRecord() {
	var (
		msg   = utils.FAILED_STRING
		flag  = utils.FAILED_FLAG
		in    = map[string]interface{}{}
		listT []models.TransferRecord //转账
		listP []models.WithdrawRecord //代付
		listR []models.RechargeRecord //充值
	)

	userId := the.GetSession("userId").(int)
	start := strings.TrimSpace(the.GetString("start"))
	end := strings.TrimSpace(the.GetString("end"))

	if start == "" {
		msg = "开始时间不能为空！"
		goto back
	}

	if start == "" {
		start = globalMethod.GetNowTimeV3() + " 00:01:05"
	}
	if end == "" {
		end = globalMethod.GetNowTime()
	}

	in["edit_time__gte"] = start
	in["edit_time__lte"] = end
	in["user_id"] = userId
	in["status"] = utils.S
	listT = transferMdl.SelectTransferRecordListPage(in, -1, 0)
	listP = payMdl.SelectWithdrawRecordListPage(in, -1, 0)
	listR = rechargeMdl.SelectRechargeRecordListPage(in, -1, 0)

	msg, flag = recordImpl.CreateXLSXFileForRecord(listT, listP, listR)

back:
	the.Data["json"] = globalMethod.JsonFormat(flag, "", msg, msg)
	the.ServeJSON()
	the.StopRun()
}

// 下载excel
// @router /merchant/download_excel/?:params [get]
func (the *Record) DownloadRecordExcel() {
	var (
		path = "static/excel/record/"
	)

	fileName := the.GetString(":params")
	file := path + fileName

	defer func() {
		if r := recover(); r != nil {
			sys.LogEmergency("操作了不存在的文件！现已恢复现场！")
			time.Sleep(10 * time.Second)
		}
	}()
	go func() {
		tk := time.NewTicker(5 * time.Minute)
		select {
		case <-tk.C:
			os.Remove(file)
			tk.Stop()
		}
	}()

	the.Ctx.Output.Download(file)
}
